//
//  YJMOauthViewController.swift
//  Weibo
//
//  Created by 杨军民 on 16/7/19.
//  Copyright © 2016年 杨军民. All rights reserved.
//

import UIKit
import SVProgressHUD

/*
1、错误：当授权成功后，还是跳回登录界面。错误的原因是：跳转时错误的时候跳转，在登录错误的时候就跳转到欢迎界面。
*/

class YJMOauthViewController: UIViewController {
    
    override func loadView() {
        //把控制器换成webView
        self.view = webView
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置背景颜色
        self.view.backgroundColor = UIColor.whiteColor()
        //调用(导航栏按钮)
        setUpApp()
        
        //使用WebView加载界面
        let stringURL = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: stringURL)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        //显示加载提示
        //设置自动关闭时间
        SVProgressHUD .setMinimumDismissTimeInterval(2)
        //设置提示框的样式
        SVProgressHUD .showWithStatus("拼命加载中")
    }
    
    //设置导航栏
    private func setUpApp() {
        //导航栏填充按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem (title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        //导航栏取消按钮
        self.navigationItem.rightBarButtonItem = UIBarButtonItem (title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //导航栏标题
        self.navigationItem.title = "登录"
    }
    
    //按钮点击事件
    //自动填充账号密码
    @objc private func autoFill() {
        let jsCode = "document.getElementById('userId').value='13538629278';document.getElementById('passwd').value='kxf950116'"
        //使用webView执行js数据
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    
    //关闭控制器
    @objc private func close() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var webView : UIWebView = UIWebView()
}

//遵守代理
extension YJMOauthViewController : UIWebViewDelegate {
    //webView加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD .dismiss()
    }
    
    //每当WebView要求加载一个网页就会调用这个方法
    func webView(webView: UIWebView,shouldStartLoadWithRequest request:NSURLRequest ,navigationType: UIWebViewNavigationType) -> Bool {
        //加载地址
        let stringURL = request.URL!.absoluteString
        //加载地址
        print("地址：\(stringURL)")
        //加载地址：https://api.weibo.com/oauth2/authorize?client_id=3654219483&redirect_uri=http://www.baidu.com
        
        //拦截授权回调
        if !stringURL.hasPrefix(redirect_uri){
            //不是授权回调就retuse
            return true
        }else{
            //区分是授权按钮还是取消按钮，用code区分
            let query = request.URL?.query
            print("query-----\(query)")
            //code=7c0df7e7f13cd383abfe476888543894 授权回调
            //判断是否以code=开头，要是以code=开头就是授权
            let codeString = "code="
            //判断
            if ((query?.hasPrefix(codeString))!) {
                //授权
                print("授权")
                //把query转换成OC字符串
                let OCQuery = query! as NSString
                let code = OCQuery.substringFromIndex(codeString.characters.count)
                print("code--------\(code)")
                
                //调用：发送POSET请求获取AccessToken
                YJMUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code,completion: {(error:NSError?) -> Void in
                    //失败的时候
                    if error != nil{
                        SVProgressHUD .showErrorWithStatus("加载AccessToken出错")
                        
                        //延迟关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                      return
                    }
                    //成功
                    self.close()
                    //跳转到欢迎界面
                    AppDelegate.switchRootViewController(YJMNweCharacteristicsController())
                })
                
            }else {
                print("取消")
                //关闭控制器
                self.close()
            }
            
            return false
        }
    }
    
}












